<template>
  <HeadContainer class="mine-earn-withdrawal-request bg-background" :title="$t('info.revDtl')" @back="back">
    <div class="gap-col-8">
      <div class="pb-2">
        <DateRangeInput v-model="dateRange"></DateRangeInput>
      </div>
      <div class="d-flex flex-row justify-space-between font-size-14 line-height-140 font-weight-500 border-b pb-2">
        <div class="gap-row-5">
          <span>{{ $t('label.earnIndex.periodProfit') }}</span>
          <span class="text-primary">${{ formatMoney(totalMoney) }}</span>
        </div>
        <div class="gap-row-5">
          <span>{{ $t('label.earnIndex.periodDeal') }}</span>
          <span class="text-primary">{{ totalDeal }}</span>
        </div>
      </div>
      <div v-for="(list, index) in detailList" :key="index">
        <div class="d-flex flex-row justify-space-between font-size-14 font-weight-400 border-b pb-2">
          <div class="text-subtitle-x gap-col-2">
            <div class="line-height-140">{{ $t('info.transactionID') }}</div>
            <div class="line-height-140">{{ $t('info.transactionDate') }}</div>
            <div class="line-height-140">{{ $t('info.transactionType') }}</div>
            <div v-if="expandedItems[index]">
              <div
                v-if="
                  list.type == TRANSACT_TYPE.REWARD ||
                  list.type == TRANSACT_TYPE.SUBSCRIBE ||
                  list.type == TRANSACT_TYPE.PRODUCT
                "
                class="line-height-140"
              >
                {{ $t('info.buyUser') }}
              </div>
              <div class="line-height-140">{{ $t('info.revenueAmount') }}</div>
              <div class="line-height-140">{{ $t('info.platformFee') }}</div>
              <div class="line-height-140">{{ $t('info.revenueNet') }}</div>
              <div v-if="list.type === TRANSACT_TYPE.PRODUCT" class="line-height-140">{{ $t('info.mediaID') }}</div>
              <div v-if="list.type === TRANSACT_TYPE.PRODUCT" class="line-height-140">{{ $t('info.mediaName') }}</div>
            </div>
          </div>
          <div class="gap-col-2 text-end font-size-14 font-weight-400">
            <div class="line-height-140">{{ list.pay_order_no }}</div>
            <div class="line-height-140">{{ list.created_at }}</div>
            <div class="line-height-140">{{ typeShow(list.type) }}</div>
            <div v-if="expandedItems[index]">
              <div
                v-if="
                  list.type == TRANSACT_TYPE.REWARD ||
                  list.type == TRANSACT_TYPE.SUBSCRIBE ||
                  list.type == TRANSACT_TYPE.PRODUCT
                "
                class="line-height-140"
              >
                @{{ list.userdetail.username === null ? '-' : list.userdetail.username }}
              </div>
              <div class="line-height-140">
                {{
                  list.type === TRANSACT_TYPE.WITHDRAW
                    ? ` - $${formatMoney(list.money)}`
                    : `$${formatMoney(list.money)}`
                }}
              </div>
              <div class="line-height-140">{{ `- $${formatMoney(list.fee)}` }}</div>
              <div class="line-height-140">{{ `$${formatMoney(list.profit)}` }}</div>
              <div v-if="list.type === TRANSACT_TYPE.PRODUCT" class="line-height-140">
                {{ list.info_id === null ? '-' : list.info_id }}
              </div>
              <div v-if="list.type === TRANSACT_TYPE.PRODUCT" class="line-height-140">
                {{
                  list.videodetail.content === '' ? '-' : list.videodetail.length === 0 ? '-' : list.videodetail.content
                }}
              </div>
            </div>
            <div @click="toggleExpand(index)" class="text-subtitle-x font-size-14 line-height-120 pointer">
              {{ expandedItems[index] ? $t('message.close') : $t('message.more') }}
              <Icon class="arrow" name="arrowDownGray" :class="{ rotate: expandedItems[index] }"></Icon>
            </div>
          </div>
        </div>
      </div>
      <div v-if="isBottom" class="d-flex justify-center align-center">
        <div class="text-input font-size-14 font-style-normal font-weight-500 line-height-140">
          {{ $t('common.noMore') }}
        </div>
      </div>
      <div v-else-if="!isFetching && detailList.length === 0" class="py-16">
        <ErrorNodata></ErrorNodata>
      </div>
      <div v-else v-intersect="onIntersect" class="d-flex justify-center align-center">
        <div v-show="isFetching">{{ $t('common.loading') }}</div>
      </div>
    </div>
  </HeadContainer>
</template>

<script setup>
import { computed, onMounted, ref, shallowRef, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { useEarnStore } from '@/store/earn.js'
import { $t } from '@/i18n'
import { toDateYmd } from '@/utils/string-helper'
import ErrorNodata from '@/components/common/ErrorNodata.vue'
import DateRangeInput from '@/components/form/DateRangeInput.vue'
import HeadContainer from '@/components/layout/HeadContainer.vue'
import { TRANSACT_TYPE } from '@/constant/index.js'
import API from '@/http'

const emits = defineEmits(['toPage'])
function back() {
  emits('toPage', 2, 'earnings')
}

const earnStore = useEarnStore()
const { startDate, endDate } = storeToRefs(earnStore)

const dateRange = shallowRef([startDate.value, endDate.value])
watch(dateRange, (newVal) => {
  startDate.value = newVal[0]
  endDate.value = newVal[1]
  reload()
})

const detailList = ref([])
const isFetching = ref(false)
const isBottom = ref(false)
const page = ref(0)
const limit = ref(10)
const totalMoney = ref(0)
const totalDeal = ref(0)

const fetch = async () => {
  try {
    isFetching.value = true
    page.value += 1

    const data = {
      page: page.value,
      limit: limit.value,
      start: toDateYmd(startDate.value),
      end: toDateYmd(endDate.value),
    }

    const response = await API.Earn.incomedetail({ data })
    isFetching.value = false
    isBottom.value = response.length <= 0

    const filteredResponse = Object.values(response).filter((item) => typeof item === 'object')
    totalMoney.value = response.total_money ? parseFloat(response.total_money) : 0
    totalDeal.value = response.total_deal
    detailList.value = [...detailList.value, ...filteredResponse]
  } catch (e) {
    console.log(e)
  }
}

onMounted(() => fetch())

const onIntersect = (value) => {
  if (value === false || isFetching.value || isBottom.value) return
  fetch()
}

const reload = () => {
  detailList.value = []
  page.value = 0
  isBottom.value = false
  isFetching.value = false
  fetch()
}

const expandedItems = ref([])
const toggleExpand = (index) => {
  expandedItems.value[index] = !expandedItems.value[index]
}

const formatMoney = (money) => {
  return Number(money).toLocaleString()
}

const typeShow = computed(() => {
  return (type) => {
    switch (type) {
      case TRANSACT_TYPE.SUBSCRIBE:
        return $t('label.subscribe')
      case TRANSACT_TYPE.PRODUCT:
        return $t('title.buyGoods')
      case TRANSACT_TYPE.WITHDRAW:
        return $t('info.withdraw')
      case TRANSACT_TYPE.WITHDRAW_ERR:
        return `${$t('info.withdraw')}${$t('message.failure')}`
      case TRANSACT_TYPE.INVITE_DIVIDED:
        return $t('info.inviteDivided')
      default:
        return $t('info.reward')
    }
  }
})
</script>

<style lang="scss" scoped>
.w-20 {
  width: 20%;
}
.w-80 {
  width: 80%;
}
.arrow {
  transition: transform 0.3s;
}
.arrow.rotate {
  transform: rotate(180deg);
}
.rotate {
  transform: rotate(180deg);
}
</style>
